# coding: utf-8

import random


class MoneyError(Exception):
    """
    create by ld_wu 2018-04-02
    """


def random_money(total_money, packet_count, min_unit=1):
    """
    create by ld_wu 2018-04-02
    1、检查红包汇币与红包数量是否符合最低为min_unit
    2、根据红包数量算出平均值avg
    3、第一份的随机范围为min_unit ~ total_money - max（total_money - avg * 2， packet_count-1）
    4、重复第三步直至分配完成
    """

    def gen_red_packets(amount, count):
        if amount < min_unit or amount < count * min_unit:
            raise MoneyError('total_money must be greater than packet_count')
        # 最后一个红包直接返回总金额
        if count == 1:
            red_packets.append(amount)
            return amount

        # 红包总金额平均分配的时的金额
        average = amount / count
        # 最大值需要保证剩余分配的金额满足至少每个人能分配1的金额
        max_money = amount - max(amount - average * 2, (count - 1) * min_unit)
        # 非最后一个红包返回min_unit ~ 平均值 * 2 的随机金额
        money = random.randint(min_unit, int(max_money))
        red_packets.append(money)
        return money

    red_packets = list()
    for _ in range(packet_count):
        red_pack_money = gen_red_packets(total_money, packet_count)
        total_money -= red_pack_money
        packet_count -= 1

    return red_packets


def average_money(total_money, packet_count):
    """
    add by zhouhl 2018-04-02
    普通群红包(平均分)
    """
    # 能整除
    if total_money == (total_money // packet_count) * packet_count:
        red_packets = [total_money // packet_count] * packet_count
    # 不能整除, 某个红包加上余数
    else:
        red_packets = [total_money // packet_count] * (packet_count - 1)
        red_packets.append(
            total_money // packet_count + total_money % packet_count
        )
        random.shuffle(red_packets)

    return red_packets

if __name__ == '__main__':
    try:
        print(random_money(100, 4))
    except MoneyError as e:
        print(e)

    print(average_money(10, 5))
    print(average_money(11, 5))
